package main

import (
	"flag"
	"os"
	"log"
)

var (
	// Port used to run the server, override the information from the flConfig file
	// if none are provided, uses the :8080 flPort
	flPort *string = flag.String("p", "", "Port that web-server will listen")

	// Server flConfiguration file
	flConfig *string = flag.String("cfg", "flConfig.json", "Configuration file")

	// Directory from this program should resolve file address
	flRoot *string = flag.String("flRoot-dir", ".", "Root directory of the server")

	// Make ostrichd run as a simple read-only file server
	flFsOnly *bool = flag.Bool("fsOnly", false, "Make ostrichd work as a read-only file server")

	// Make ostrichd handle https protocol.
	flHttps *bool = flag.Bool("https", false, "Make the ostrichd use the https protocol instead of pure http")

	// Https key.pem file
	flKeyFile *string = flag.String("keyFile", "key.pem", "x509 pem encoded key file. Use ostrich-utl gen-cert <your host> <your company> to generate")

	// Https cert.pem file
	flCertFile *string = flag.String("certFile", "cert.pem", "x509 pem encoded cert file. Use ostrich-utl gen-cert <your host> <your company> to generate")
)

func main() {
	flag.Parse()
	if len(*flPort) == 0 {
		*flPort = ":8080"
	}

	cfg, err := loadConfig(*flConfig)
	if err != nil {
		// log the error but don't stop the server
		// since it's not very imflPortant to have flConfiguration
		// right now.
		// TODO: this may change in the future
		log.Printf("Error while loading flConfig %v\n", err)
	}

	// flConfigure the flPort and flRoot folder, uses the command-line as default
	cfg.PutIfNone(CFGK_PORT, *flPort)
	cfg.PutIfNone(CFGK_ROOT_FOLDER, *flRoot)
	cfg.PutIfNone(CFGK_FS_ONLY, *flFsOnly)
	cfg.PutIfNone(CFGK_HTTPS, *flHttps)
	cfg.PutIfNone(CFGK_CERT_FILE, *flCertFile)
	cfg.PutIfNone(CFGK_KEY_FILE, *flKeyFile)

	exitCode := make(chan int)

	startHttpServer(exitCode, cfg)

	os.Exit(<-exitCode)
}
